package com.zhou.project.configurations.security.authentication;

import com.zhou.project.modules.system.user.entity.SysUser;
import com.zhou.project.modules.system.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * @project spring-boot-project
 * @author zhouhonggang
 * @datetime 2021/9/24 14:44
 * @version 1.0.0
 * @description: 获取登陆人信息
 */
@Component
public class CurrentAuthentication {

    @Autowired
    private SysUserService sysUserService;

    //绑定当前登陆人到当前线程中
    private static final ThreadLocal<Integer> currentUser = new ThreadLocal<>();

    /**
     * 获取当前登陆对象主键
     * @return 用户主键
     */
    public Integer getCurrentUserId()
    {
        return getCurrentUser().getId();
    }

    /**
     * 获取当前登陆对象
     * @return 登陆对象
     */
    public SysUser getCurrentUser()
    {
        //获取当前登陆人(登录账号)
        String account = SecurityContextHolder.getContext().getAuthentication().getName();
        if(account.equals("anonymousUser"))
        {
            SysUser entity = new SysUser();
            entity.setId(1);
            return entity;
        }
        //返回当前登陆人(用户对象)
        return sysUserService.getUserByAccount(account);
    }

}
